<script setup lang="ts">
import { ref, onMounted, useTemplateRef } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

let map: any
const mapContainer = useTemplateRef('mapContainer')
const loading = ref(false)
const location = ref({
  latitude: 39.90923,
  longitude: 116.397428,
})

const initMap = () => {
  // @ts-ignore
  window._AMapSecurityConfig = {
    securityJsCode: '3a06f860bef05b3a1ccc723e13ad3f75',
  }
  AMapLoader.load({
    key: '7dc78176646b946eaa970c21a72f47c4', //此处填入我们注册账号后获取的Key
    version: '2.0',
    plugins: ['AMap.Geocoder', 'AMap.Marker'],
  })
    .then((AMap) => {
      map = new AMap.Map(mapContainer.value, {
        center: [location.value.longitude, location.value.latitude], //地图中心点
        zoom: 11, //地图缩放级别
      })
      const marker = new AMap.Marker({
        position: [location.value.longitude, location.value.latitude],
      })
      map.add(marker)
      loading.value = false
      const geocoder = new AMap.Geocoder({
        city: '010', // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
      })
      const lnglat = [location.value.longitude, location.value.latitude]
      geocoder.getAddress(lnglat, function (status: any, result: any) {
        if (status === 'complete' && result.info === 'OK') {
          // TODO: 自动调用更新用户接口更新用户的地理位置
          // result为对应的地理位置详细信息
          // console.log(result.regeocode.formattedAddress)
        }
      })
    })
    .catch((e) => {
      console.error(e)
      loading.value = false
    })
}

// 查看用户是否允许获取地理位置
const checkPermission = () => {
  return new Promise(async (resolve) => {
    const result = await navigator.permissions.query({ name: 'geolocation' })
    result.addEventListener('change', () => {
      console.log('permissionStatusChange', result)
    })
    resolve(result.state)
  })
}

// 获取当前用户的地理位置
const getCurrentPosition = async () => {
  return new Promise(async (resolve, reject) => {
    if (navigator.geolocation) {
      const state = await checkPermission()
      if (state === 'denied') {
        return Promise.reject('用户拒绝')
      }
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords
          location.value.latitude = latitude
          location.value.longitude = longitude
          resolve(location.value)
        },
        (error) => {
          reject('Error getting location:' + error)
        },
      )
    }
  })
}

onMounted(async () => {
  loading.value = true
  // 获取点位信息
  await getCurrentPosition()
  initMap()
})
</script>

<template>
  <div class="map-component" v-loading="loading">
    <div class="map-container" ref="mapContainer"></div>
  </div>
</template>

<style scoped lang="scss">
.map-component {
  width: 50%;
  height: 300px;
  overflow: hidden;
  background-color: #1a1a1a;
  border-radius: 12px;
  color: #fff;
  border: 1px solid var(--xfxjLineColor);

  .map-container {
    width: 100%;
    height: 100%;
  }
}
</style>
